package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.base.BaseEntity;
import com.ruoyi.common.constant.CacheKeyConstants;
import com.ruoyi.common.constant.ResultConstants;
import com.ruoyi.common.enums.TxnType;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.support.Convert;
import com.ruoyi.common.utils.BigDecimalUtil;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.RandomStringUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.WdyBuyProduct;
import com.ruoyi.system.domain.WdyDirectReward;
import com.ruoyi.system.domain.WdyTxnHistory;
import com.ruoyi.system.domain.WdyUser;
import com.ruoyi.system.mapper.WdyBuyProductMapper;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 购买记录 服务层实现
 * 
 * @author ruoyi
 * @date 2019-12-15
 */
@Service
public class WdyBuyProductServiceImpl extends ServiceImpl<WdyBuyProductMapper, WdyBuyProduct> implements IWdyBuyProductService
{
	@Autowired
	private IWdyUserService wdyUserService;

	@Autowired
	private IWdyTxnHistoryService wdyTxnHistoryService;

	@Autowired
	private IWdyDirectRewardService wdyDirectRewardService;
	@Autowired
	private IWdyReferrerRewardService wdyReferrerRewardService;

	@Autowired
	protected RedisTemplate redisTemplate;
	/**
     * 查询购买记录信息
     * 
     * @param id 购买记录ID
     * @return 购买记录信息
     */
    @Override
	public WdyBuyProduct selectWdyBuyProductById(Long id)
	{
	    return baseMapper.selectWdyBuyProductById(id);
	}
	
	/**
     * 查询购买记录列表
     * 
     * @param wdyBuyProduct 购买记录信息
     * @return 购买记录集合
     */
	@Override
	public List<WdyBuyProduct> selectWdyBuyProductList(WdyBuyProduct wdyBuyProduct)
	{
	    return baseMapper.selectWdyBuyProductList(wdyBuyProduct);
	}
	
    /**
     * 新增购买记录
     * 
     * @param wdyBuyProduct 购买记录信息
     * @return 结果
     */
	@Override
	public int insertWdyBuyProduct(WdyBuyProduct wdyBuyProduct)
	{
	    return baseMapper.insertWdyBuyProduct(wdyBuyProduct);
	}
	
	/**
     * 修改购买记录
     * 
     * @param wdyBuyProduct 购买记录信息
     * @return 结果
     */
	@Override
	public int updateWdyBuyProduct(WdyBuyProduct wdyBuyProduct)
	{
	    return baseMapper.updateWdyBuyProduct(wdyBuyProduct);
	}

	/**
     * 删除购买记录对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteWdyBuyProductByIds(String ids)
	{
		return baseMapper.deleteWdyBuyProductByIds(Convert.toStrArray(ids));
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void buy(WdyBuyProduct buyProduct) {
//		QueryWrapper<WdyUser> queryWrapper = new QueryWrapper<>();
//		queryWrapper.eq("user_id", buyProduct.getUserId());
//		queryWrapper.eq("del_flag", BaseEntity.NOT_DELETED);
//		WdyUser user = wdyUserService.getOne(queryWrapper);
//
//		if(user.getCnnAmount().compareTo(buyProduct.getCnnAmount()) < 0) {
//			throw new BusinessException(ResultConstants.FI2004, "CNN余额不足");
//		}
//
//		WdyUser updateUser = new WdyUser();
//		updateUser.setCnnAmount(BigDecimalUtil.subtract(user.getCnnAmount(), buyProduct.getCnnAmount()));
//		updateUser.setVersion(user.getVersion());
//		if(!wdyUserService.update(updateUser, queryWrapper)) {
//			throw new BusinessException(ResultConstants.FI2007, "系统繁忙，请稍后重试");
//		}

		this.save(buyProduct);

//		WdyTxnHistory txnHistory = new WdyTxnHistory();
//		txnHistory.setUserId(user.getUserId());
//		txnHistory.setTxnId(String.valueOf(buyProduct.getId()));
//		txnHistory.setTxnAmount(BigDecimalUtil.subtract(0, buyProduct.getCnnAmount()));
//		txnHistory.setTxnType(TxnType.BUY_PRODUCT.getCode());
//		txnHistory.setAmountType(TxnType.BUY_PRODUCT.getAmountType().getCode());
//		txnHistory.setTxnDesc(TxnType.BUY_PRODUCT.getName());
//		wdyTxnHistoryService.save(txnHistory);

		wdyDirectRewardService.reward(buyProduct.getUserId(), buyProduct.getCnnAmount(), buyProduct.getId(), WdyDirectReward.BUY_PRODUCT);
		wdyReferrerRewardService.reward(buyProduct.getUserId(), buyProduct.getCnnAmount(), buyProduct.getId(), WdyDirectReward.BUY_PRODUCT);

		redisTemplate.delete(CacheKeyConstants.BUY_PRODUCT);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void active(WdyBuyProduct wdyBuyProduct) {
		if(StringUtils.isEmpty(wdyBuyProduct.getActiveCode())) {
			throw new BusinessException(ResultConstants.FI1000, "activeCode " + MessageUtils.message("not.null"));
		}
		QueryWrapper<WdyBuyProduct> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("user_id", wdyBuyProduct.getUserId());
		queryWrapper.eq("active_code", wdyBuyProduct.getActiveCode());
		queryWrapper.eq("active_state", BaseEntity.NO);
		WdyBuyProduct originBuyProduct = this.getOne(queryWrapper);
		if(originBuyProduct == null) {
			throw new BusinessException(ResultConstants.FI1000, "理财产品不存在");
		}
		WdyBuyProduct updateBuyProduct = new WdyBuyProduct();
		updateBuyProduct.setActiveState(BaseEntity.YES);
		if(!this.update(updateBuyProduct, queryWrapper)) {
			throw new BusinessException(ResultConstants.FI1000, "理财产品不存在");
		}
	}

	@Override
	public void incrReleaseAmount(String userId) {
		incrReleaseAmount(userId, BigDecimal.valueOf(2));
	}

	@Override
	public Map<String, BigDecimal> getSum(WdyBuyProduct wdyBuyProduct) {
		return baseMapper.getSum(wdyBuyProduct);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void buyUseCnn(WdyBuyProduct buyProduct) {
		QueryWrapper<WdyUser> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("user_id", buyProduct.getUserId());
		queryWrapper.eq("del_flag", BaseEntity.NOT_DELETED);
		WdyUser user = wdyUserService.getOne(queryWrapper);

		if(user.getCnnAmount().compareTo(buyProduct.getCnnAmount()) < 0) {
			throw new BusinessException(ResultConstants.FI2004, "CNN余额不足");
		}

		WdyUser updateUser = new WdyUser();
		updateUser.setCnnAmount(BigDecimalUtil.subtract(user.getCnnAmount(), buyProduct.getCnnAmount()));
		updateUser.setVersion(user.getVersion());
		if(!wdyUserService.update(updateUser, queryWrapper)) {
			throw new BusinessException(ResultConstants.FI2007, "系统繁忙，请稍后重试");
		}

		buyProduct.setActiveCode(RandomStringUtils.getRandomString(6));
		buyProduct.setActiveState(BaseEntity.YES);
		this.save(buyProduct);

		WdyTxnHistory txnHistory = new WdyTxnHistory();
		txnHistory.setUserId(user.getUserId());
		txnHistory.setTxnId(String.valueOf(buyProduct.getId()));
		txnHistory.setTxnAmount(BigDecimalUtil.subtract(0, buyProduct.getCnnAmount()));
		txnHistory.setTxnType(TxnType.BUY_PRODUCT.getCode());
		txnHistory.setAmountType(TxnType.BUY_PRODUCT.getAmountType().getCode());
		txnHistory.setTxnDesc(TxnType.BUY_PRODUCT.getName());
		wdyTxnHistoryService.save(txnHistory);
	}


	@Override
	public void incrReleaseAmount(String userId, BigDecimal incrAmount) {
		QueryWrapper<WdyBuyProduct> queryWrapper = new QueryWrapper<>();
		queryWrapper.select("id", "release_amount");
		queryWrapper.eq("user_id", userId);
		queryWrapper.eq("active_state", BaseEntity.YES);
		queryWrapper.gt("freeze_vc_amount", 0);
		queryWrapper.last("limit 1");
		queryWrapper.orderByAsc("id");
		WdyBuyProduct wdyBuyProduct = this.getOne(queryWrapper);
		BigDecimal max = BigDecimal.valueOf(150);
		if(wdyBuyProduct != null && wdyBuyProduct.getReleaseAmount().compareTo(max) < 0) {
			BigDecimal releaseAmount = BigDecimalUtil.add(wdyBuyProduct.getReleaseAmount(), incrAmount);
			if(releaseAmount.compareTo(max) > 0) {
				releaseAmount = max;
			}
			wdyBuyProduct.setReleaseAmount(releaseAmount);
			this.updateById(wdyBuyProduct);
		}
	}
}
